<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .wrap {
            width: 320px;
            height: 500px;
            border: 1px solid #333;
            margin: 50px auto;
            position: relative;
        }

        .box {
            width: 40px;
            height: 40px;
            background-color: pink;
            position: absolute;
            /* left: 0; */
            /* top: 0; */
            left: 140px;
            top: 460px;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <div class="box"></div>
    </div>
</body>
<script>
    var box = document.getElementsByClassName("box")[0];
    document.onkeydown = function (e) {
        var e = e || window.event;
        var keyCode = e.keyCode;  // 按键对应的键盘码
        console.log(keyCode);

        // 按下 左 上 右 下 => 控制盒子相对于原位置移动

        var x = box.offsetLeft;
        var y = box.offsetTop;
        var speed = 10;

        if (keyCode == 37) { // 左
            x -= speed;
        } else if (keyCode == 38) { // 上
            y -= speed;

        } else if (keyCode == 39) { // 右
            x += speed;
        } else if (keyCode == 40) { // 下
            y += speed;
        }

        box.style.left = x +"px";
        box.style.top = y +"px";

    }


</script>

</html>